package com.ruoyi.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class RedisUtil {
	private static final Logger LOG = LoggerFactory.getLogger(RedisUtil.class);
	/**
	 * 获取Redis的key
	 * @param model
	 * @return
	 */
	public static <T> String redisKey(T model) {
		String key = "";
		try {
			Class<? extends Object> clazz = model.getClass();
			// 得到实体泛型所有属性
			Field[] field = clazz.getDeclaredFields();
			for(int i=0;i<field.length;i++){
				// 设置可以访问私有变量
				field[i].setAccessible(true);
				// 获取属性的名字
				String name = field[i].getName();
				if(name.equals("serialVersionUID"))
					continue;
				// 将属性名字的首字母大写
				name = name.replaceFirst(name.substring(0, 1), name.substring(0, 1).toUpperCase());
				// 组装Get方法
				Method m = clazz.getMethod("get" + name);
				// 调用Get方法
				Object o = m.invoke(model);
				if (!VerifyUtil.isEmpty(o))
					key += "_" + o;
			}
		} catch (Exception e) {
			LOG.info("redisKey -> model" + model + "：没有属性值");
			return "";
		}
		return key;
	}

	/**
	 * 获取Redis的key
	 * @param o
	 * @return
	 */
	public static String redisKeyByObject(Object o) {
		String key = "";
		if (!VerifyUtil.isEmpty(o))
			key += "_" + o;
		return key;
	}

}